package com.augrain.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YaoBiao
 * @date 2021/4/7 11:40
 */
@Controller
public class AnnotatedController {

    @GetMapping("simple")
    @ResponseBody
    public Map<String, Object> simpleData() {
        Map<String, Object> simple = new HashMap<>();

        simple.put("name", "demo");

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String attributeName = attributeNames.nextElement();
            Object attribute = request.getAttribute(attributeName);

            System.out.printf("name: %s, value: %s, class: %s%n", attributeName, attribute, attribute.getClass().getName());
        }
        return simple;
    }

    @GetMapping("simple/{id}")
    @ResponseBody
    public Map<String, Object> get(@PathVariable("id") String id) {
        Map<String, Object> simple = new HashMap<>();
        simple.put("name", "demo");
        simple.put("id", id);
        return simple;
    }
}
